/*
* 生产任务列表
* */
import 'package:center_beijing/api/component_api.dart';
import 'package:center_beijing/api/product_api.dart';
import 'package:center_beijing/common/QRScan.dart';
import 'package:center_beijing/common/custom_floatingAction_buttonLocation.dart';
import 'package:center_beijing/common/logutil.dart';
import 'package:center_beijing/common/notification.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/common/utils.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/config/routeConfig.dart';
import 'package:center_beijing/models/selectItem.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:center_beijing/widgets/pull_select_widget.dart';
import 'package:center_beijing/widgets/search_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_pickers/pickers.dart';

class ProductionHome extends StatefulWidget {
  @override
  _ProductionHomeState createState() => _ProductionHomeState();
}

class _ProductionHomeState extends State<ProductionHome> {
  CustomLoading loading = CustomLoading.withMessage('请稍候...');
  EasyRefreshController _controller = EasyRefreshController();
  TextEditingController _textInput = TextEditingController();
  List<SelectItems> typeList = [];
  SelectItems selectType = SelectItems(label: '全部类型', value: '');
  List<SelectItems> taskList = [];
  SelectItems selectTask = SelectItems();
  var selectBuild = '';
  List dataSource = [];
  int page = 1;
  int pageSize = 15;
  bool firstLoad = true;

  @override
  void initState() {
    super.initState();
    this.getAllTask();
    this.getAllComp();
    bus.on('refreshDetail', (arg) {
      page = 1;
      // _controller.finishLoad(success: true, noMore: false);
      this.getInfoList();
    });
  }

  @override
  void dispose() {
    bus.off('refreshDetail');
    _controller.dispose();
    loading.dismiss();
    super.dispose();
  }

  /*
  * 获取类型列表
  * */
  getAllComp() async {
    var result = await getComponentType(
        {'projectId': GlobalConfig.selectFactory.value, 'kindType': ''});
    List<SelectItems> list = [];
    if (result != null && result.length > 0) {
      for (var item in result) {
        list.add(SelectItems(label: item['compKindName'], value: item['id']));
      }
      list.insert(0, SelectItems(label: '全部类型', value: ''));
      this.setState(() {
        typeList = list;
      });
    } else {
      this.setState(() {
        firstLoad = false;
      });
    }
    LogUtil.d(result);
  }

  getAllTask() async {
    var result = await getProjectTasks(GlobalConfig.selectFactory.value);
    List<SelectItems> list = [];
    if (result != null && result.length > 0) {
      for (var item in result) {
        list.add(SelectItems(label: item['taskCode'], value: item['id']));
      }
      list.insert(0, SelectItems(label: '全部任务', value: ''));
      this.setState(() {
        taskList = list;
        selectTask = taskList[1];
        this.getInfoList();
      });
    } else {
      this.setState(() {
        firstLoad = false;
      });
    }
    LogUtil.d(result);
  }

  getInfoList() async {

    var pass = {
      'dayPlanId': selectTask.value,
      'code': _textInput.text,
      'compKindId': selectType.value,
      'page': page,
      'page-size': pageSize,
      'chargePersonId': GlobalConfig.userInfo['userId'],
      'projectId':GlobalConfig.selectFactory.value
    };
    var result = await getTasksList(pass);
    loading.dismiss();
    if (this.page == 1) {
      dataSource.clear();
    }
    firstLoad = false;
    if (result != null) {
      if (result['data'].length == 0) {
        // _controller.finishLoad(success: true, noMore: true);
      } else {
        dataSource.addAll(result['data']);
      }
    }
    this.setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('生产任务'),
      ),
      body: Container(
        color: Styles.MainBackgroundColor,
        padding:
            EdgeInsets.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              color: Colors.white,
              child: Row(
                children: [
                  Expanded(
                    flex: 2,
                    child: Container(
                      margin: EdgeInsets.fromLTRB(Styles.spacing16,
                          Styles.spacing8, Styles.spacing16, Styles.spacing8),
                      child: SearchWidget(
                        textInput: _textInput,
                        placeholder: '请输入构件编号',
                        textSubmit: (value) {
                          page = 1;
                          // _controller.finishLoad(success: true, noMore: false);
                          this.getInfoList();
                        },
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Container(
              color: Colors.white,
              padding: EdgeInsets.fromLTRB(Styles.spacing16, Styles.spacing4,
                  Styles.spacing16, Styles.spacing4),
              child: Row(
                children: [
                  Expanded(
                    flex: 1,
                    child: Container(
                      color: Colors.white,
                      child: PullSelectWidget(
                        text_align: TextAlign.center,
                        rightText: selectTask.label,
                        backColor: Colors.white,
                        items: taskList,
                        selectCallback: (value) {
                          this.selectTask = value;
                          page = 1;
                          loading.show(delay: 15);
                          this.getInfoList();
                        },
                      ),
                    ),
                  ),
                  Expanded(
                    flex: 1,
                    child: Container(
                      color: Colors.white,
                      child: PullSelectWidget(
                        text_align: TextAlign.center,
                        rightText: selectType.label,
                        backColor: Colors.white,
                        items: typeList,
                        selectCallback: (value) {
                          this.selectType = value;
                          page = 1;
                          loading.show(delay: 15);
                          this.getInfoList();
                        },
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
                child: NotificationListener(
              onNotification: (_) {
                FocusScope.of(context).requestFocus(new FocusNode());
                return false;
              },
              child: this.dataSource.length > 0
                  ? EasyRefresh.custom(
                      shrinkWrap: true,
                      firstRefresh: false,
                      controller: _controller,
                      header: MaterialHeader(),
                      footer: ClassicalFooter(
                          loadingText: '加载中',
                          loadText: '上拉加载',
                          noMoreText: '没有更多数据',
                          loadedText: '加载完成',
                          infoText: '更新于 %T',
                          textColor: Styles.NoMoreColor,
                          showInfo: false),
                      emptyWidget: (dataSource.length == 0 && !firstLoad)
                          ? Center(
                              child: Image(
                                image: AssetImage('assets/images/no_data.png'),
                                width: 128,
                                height: 150,
                              ),
                            )
                          : null,
                      onRefresh: () async {
                        // _controller.finishLoad(success: true, noMore: false);
                        if (mounted) {
                          page = 1;
                          this.getInfoList();
                        }
                      },
                      onLoad: () async {
                        await Future.delayed(Duration(seconds: 2), () {
                          if (mounted) {
                            page++;
                            this.getInfoList();
                          }
                        });
                      },
                      slivers: <Widget>[
                          SliverList(
                            delegate: SliverChildBuilderDelegate(
                              (context, index) {
                                return GestureDetector(
                                  onTap: () {
                                    Get.toNamed(RouteConfig.productionDetail,
                                        arguments: this.dataSource[index]
                                            ['id']);
                                  },
                                  child: Container(
                                    color: Colors.white,
                                    padding: EdgeInsets.fromLTRB(
                                        Styles.spacing16,
                                        Styles.spacing8,
                                        Styles.spacing16,
                                        Styles.spacing8),
                                    margin: EdgeInsets.fromLTRB(
                                        Styles.spacing8,
                                        Styles.spacing4,
                                        Styles.spacing8,
                                        Styles.spacing4),
                                    child: Row(
                                      children: [
                                        Expanded(
                                          child: Column(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            children: [
                                              Row(
                                                children: [
                                                  Expanded(
                                                      child: Column(
                                                    crossAxisAlignment:
                                                        CrossAxisAlignment
                                                            .start,
                                                    children: [
                                                      Text(
                                                        this.dataSource[index]
                                                                    ['code'] !=
                                                                null
                                                            ? this.dataSource[
                                                                index]['code']
                                                            : '--',
                                                        style: TextStyle(
                                                            color: Styles
                                                                .DetailColor,
                                                            fontSize: Styles
                                                                .Middle15Font),
                                                      ),
                                                      Text(
                                                        this.dataSource[index][
                                                                    'compKind'] !=
                                                                null
                                                            ? this.dataSource[
                                                                        index]
                                                                    ['compKind']
                                                                ['compKindName']
                                                            : '--',
                                                        style: TextStyle(
                                                            color: Styles
                                                                .DetailColor,
                                                            fontSize: Styles
                                                                .Middle15Font),
                                                      ),
                                                    ],
                                                  )),
                                                  Row(
                                                    children: [
                                                      Container(
                                                        color: Styles.BlueColor,
                                                        margin:
                                                            EdgeInsets.fromLTRB(
                                                                Styles.spacing4,
                                                                0,
                                                                Styles.spacing4,
                                                                0),
                                                        padding:
                                                            EdgeInsets.fromLTRB(
                                                                Styles.spacing4,
                                                                Styles.spacing4,
                                                                Styles.spacing4,
                                                                Styles
                                                                    .spacing4),
                                                        child: Text(
                                                          (this.dataSource[index]
                                                                          [
                                                                          'state'] !=
                                                                      null &&
                                                                  this.dataSource[
                                                                              index]
                                                                          [
                                                                          'state'] ==
                                                                      2)
                                                              ? '维修中'
                                                              : '正常',
                                                          style: TextStyle(
                                                              color:
                                                                  Colors.white,
                                                              fontSize: Styles
                                                                  .SmallFont),
                                                        ),
                                                      ),
                                                      Container(
                                                        color:
                                                            Styles.OrangeColor,
                                                        margin:
                                                            EdgeInsets.fromLTRB(
                                                                Styles.spacing4,
                                                                0,
                                                                Styles.spacing4,
                                                                0),
                                                        padding:
                                                            EdgeInsets.fromLTRB(
                                                                Styles.spacing4,
                                                                Styles.spacing4,
                                                                Styles.spacing4,
                                                                Styles
                                                                    .spacing4),
                                                        child: Text(
                                                          this.dataSource[index]
                                                                      [
                                                                      'processStatus'] !=
                                                                  null
                                                              ? (this.dataSource[
                                                                              index]
                                                                          [
                                                                          'processStatus'] ==
                                                                      1
                                                                  ? '待生产'
                                                                  : '生产中')
                                                              : '未知',
                                                          style: TextStyle(
                                                              color:
                                                                  Colors.white,
                                                              fontSize: Styles
                                                                  .SmallFont),
                                                        ),
                                                      )
                                                    ],
                                                  )
                                                ],
                                              ),
                                              Text(
                                                this.dataSource[index]
                                                            ['orderInfo'] !=
                                                        null
                                                    ? this.dataSource[index]
                                                            ['orderInfo']
                                                        ['orderName']
                                                    : '--',
                                                style: TextStyle(
                                                    color:
                                                        Styles.LeftTitleColor,
                                                    fontSize:
                                                        Styles.NormalFont),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                );
                              },
                              childCount: dataSource.length,
                            ),
                          ),
                        ])
                  : firstLoad
                      ? Center(
                          child: CircularProgressIndicator(),
                        )
                      : Center(
                          child: Image(
                            image: AssetImage('assets/images/no_data.png'),
                            width: 128,
                            height: 150,
                          ),
                        ),
            ))
          ],
        ),
      ),
      floatingActionButtonLocation: CustomFloatingActionButtonLocation(
        FloatingActionButtonLocation.endFloat,
      ),
      floatingActionButtonAnimator: NoScalingAnimation(),
      floatingActionButton: FloatingActionButton(
          child: Image.asset(
            'assets/images/saoyisao.png',
            fit: BoxFit.fill,
          ),
          onPressed: () async {
            var result = await QrScan.scan(context,type: 3);
            if (result != null) {
              if (result['type'] == 1) {
                Get.toNamed(RouteConfig.productionDetail,
                    arguments: result['code']);
              } else if(result['type'] == 2){
                Get.toNamed(RouteConfig.equipmentDetail,
                    arguments: result['code']);
              }else {
                showDialog(
                    barrierDismissible: false,
                    context: context,
                    builder: (BuildContext context) {
                      return AlertDialog(
                        title: Text('注意'),
                        content: Text('请扫正确的二维码！'),
                        actions: <Widget>[
                          new Container(
                            child: FlatButton(
                              child: new Text(
                                "确定",
                                style: TextStyle(color: Colors.red),
                              ),
                              onPressed: () {
                                Navigator.pop(context);
                              },
                            ),
                          ),
                        ],
                      );
                    });
              }
            }
          },
          backgroundColor: Colors.transparent),
    );
  }
}
